import os
from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from shortuuid import uuid
from django.conf import settings

from apps.image.serializers import UploadImageSerializer


# Create your views here.

class UploadImageView(APIView):
    def post(self, request):
        serializer = UploadImageSerializer(data=request.data)
        if serializer.is_valid():
            file = serializer.validated_data['image']
            # os.path.splitext('book.png')  -> ('book', 'png')
            filename = uuid() + os.path.splitext(file.name)[-1]
            path = settings.MEDIA_ROOT / filename
            try:
                with open(path, 'wb') as fb:
                    for chunk in file.chunks():
                        fb.write(chunk)
            except Exception as e:
                return Response({'errno': 1, 'message': str(e)})
            # book.png -> /media/book.png
            print(filename, type(filename))
            file_url = settings.MEDIA_URL + filename
            return Response({
                'errno': 0,
                'data': {
                    "url": file_url,  # 图片的 src 必须
                    "alt": "",  # 图片的描述文字, 非必须
                    "href": file_url,  # 图片链接, 非必须
                }})
        else:
            print(serializer.errors)
            return Response({
                "errno": 1,  # 只要不等于 0 就行
                "message": list(serializer.errors.values())[0][0]
            })
